package com.shopping_back.controller;


import com.shopping_back.common.Result;
import com.shopping_back.pojo.dto.PromotionCreateDTO;
import com.shopping_back.pojo.dto.PromotionUpdateDTO;
import com.shopping_back.pojo.entity.PromotionActivity;
import com.shopping_back.service.IPromotionActivityService;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * <p>
 * 促销活动表 前端控制器
 * </p>
 *
 * @author Jack
 * @since 2025-07-12
 */
@RestController
@RequestMapping("/api/promotion-activity")
@RequiredArgsConstructor
public class PromotionActivityController {

    final IPromotionActivityService promotionActivityService;

    @GetMapping
    public Result getPromotions(
            @RequestParam(value = "type", required = false) Integer type,
            @RequestParam(value = "page", defaultValue = "1") Integer page,
            @RequestParam(value = "size", defaultValue = "10") Integer size
    ) {
        try {
            // 查询促销活动，支持类型过滤
            Map<String, Object> resultPage = promotionActivityService.getPromotionsByType(page, size, type);

            return Result.success(resultPage);
        } catch (Exception e) {
            return Result.error("获取促销活动失败: " + e.getMessage());
        }
    }

    @GetMapping("/{id}")
    public Result getPromotionDetail(@PathVariable Long id) {
        PromotionActivity promotion = promotionActivityService.getById(id);
        return promotion != null ? Result.success(promotion) : Result.error("404", "Promotion not found");
    }

    /** 分页列表（按名称/类型搜索） */
    @GetMapping("/admin/list")
    public Result list(@RequestParam(defaultValue = "1") Integer pageNum,
                       @RequestParam(defaultValue = "10") Integer pageSize,
                       @RequestParam(required = false) String name,
                       @RequestParam(required = false) String type) {
        return Result.success(promotionActivityService.listPage(pageNum, pageSize, name, type));
    }

    /** 新增活动（只能操作 name/type/start/end） */
    @PostMapping("/admin")
    public Result create(@RequestBody @Validated PromotionCreateDTO dto) {
        promotionActivityService.create(dto);
        return Result.success();
    }

    /** 编辑活动（不能改 type） */
    @PutMapping("/admin")
    public Result update(@RequestBody @Validated PromotionUpdateDTO dto) {
        promotionActivityService.updateBasic(dto);
        return Result.success();
    }

    /** 删除活动（需物理删除子表数据） */
    @DeleteMapping("/admin/{id}")
    public Result delete(@PathVariable Long id) {
        promotionActivityService.deleteCascade(id);
        return Result.success();
    }

}
